package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {

    //调用mapper层
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private  SpuImageMapper spuImageMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private BaseTradeMarkMapper baseTradeMarkMapper;

    //获取一级分类数据
    @Override
    public List<BaseCategory1> getCategory1() {
        //select * from base_category1
        return baseCategory1Mapper.selectList(null);
    }

    /**
     * 根据一级分类数据id获取二级分类数据
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //select * from  base_category2 where category1_id = category1Id
        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        baseCategory2QueryWrapper.eq("category1_id", category1Id);
        return baseCategory2Mapper.selectList(baseCategory2QueryWrapper);
    }

    /**
     * 根据二级分类数据id获取三级分类数据
     * @param category2Id
     * @return
     */
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //select * from base_category3 where category2_id = category2Id
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
    }

    /**
     * //根据分类id获取平台属性集合
     * @param category1Id
     * @param category2Id
     * @param category3Id
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        //根据分析可能需要具备的知识点：mybatis的动态sql标签
        //多表关联查询：因此 使用*mqpper.xml
        //开发的默认规则 ： service层：get  save    mapper层：select insert
        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id);
    }

    /**
     * 保存平台属性
     * @param baseAttrInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//有异常就回滚
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //这个控制器，有添加功能，也有修改功能
        if(baseAttrInfo.getId()==null){
            //插入数据：
            baseAttrInfoMapper.insert(baseAttrInfo);
        }else {
            //修改数据
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }
        //base_attr_value 先删除，再新增！
        //delete from base_attr_value where attr_id = ?;
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(queryWrapper);

        //获取平台属性值集合数据
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            //attrId传递的是null
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }

    /**
     * 根据平台属性id获取平台属性值
     * @return
     */
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //直接返回数据
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));
    }

    /**
     * 根据平台属性id获取平台属性对象
     * @param attrId
     * @return
     */
    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //select * from base_arrt_into where id = arrtId;
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        if(baseAttrInfo!=null){
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        //返回数据
        return baseAttrInfo;
    }

    /**
     * 查询数据
     * @param ipage
     * @param spuInfo
     * @return
     */
    @Override
    public IPage getSpuInfoPage(Page ipage, SpuInfo spuInfo) {
        //select * from spu_info where category3_id = 61 order by id desc limit 0 , 10
        QueryWrapper<SpuInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("category3_id", spuInfo.getCategory3Id());
        //排序 升序 需要写到limit前
        wrapper.orderByDesc("id");
        return spuInfoMapper.selectPage(ipage, wrapper);
    }

    /**
     * 查询所有的销售属性
     * @return
     */
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        //select * from base_sale_attr;
       return baseSaleAttrMapper.selectList(null);
    }

    /**
     * 保存spuInfo
     * @param spuInfo
     */
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        /*
        spuInfo:商品表
        spuImage:商品图片表
        spuSaleAttr:销售属性
        spuSaleAttrValue:销售属性值
        spuPoster:商品海报
         */
        spuInfoMapper.insert(spuInfo);
        //商品图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断
        if(!CollectionUtils.isEmpty(spuImageList)){
            //遍历循环
            spuImageList.stream().forEach(spuImage -> {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        //销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //判断
        if(!CollectionUtils.isEmpty(spuSaleAttrList)){
            //遍历循环
            spuSaleAttrList.stream().forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                //获取销售属性值集合
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //判断
                if(!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    //循环遍历添加
                    spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                        //赋值
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
        //获取海报信息
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        //判断
        if(!CollectionUtils.isEmpty(spuPosterList)){
            //循环遍历
            spuPosterList.stream().forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                //添加
                spuPosterMapper.insert(spuPoster);
            });
        }
    }

    /**
     * 获取spuImage集合
     * @param spuId
     * @return
     */
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
       return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
    }

    /**
     * 根据spuId获取销售属性集合
     * @param spuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        //调用mapper  多表联查
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    /**
     * 保存skuInfo
     * @param skuInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
            将数据插入数据局表
            skuInfo: 库存单元表  记录是哪个spu下的sku
            skuImage：库存单元图片表
            skuSaleAttrValue ： sku与销售属性值中间表
            skuAttrValue : sku与平台属性值中间表
         */
        skuInfoMapper.insert(skuInfo);
        //获取skuImage 集合
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        //判断
        if(!CollectionUtils.isEmpty(skuImageList)){
            //遍历
            skuImageList.stream().forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }

        //skuSaleAttrVlaue
        if(!CollectionUtils.isEmpty(skuInfo.getSkuSaleAttrValueList())){
            skuInfo.getSkuSaleAttrValueList().stream().forEach(skuSaleAttrValue -> {
                //spuId skuId
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }

        //skuAttrVlaue
        if (!CollectionUtils.isEmpty(skuInfo.getSkuAttrValueList())) {
            skuInfo.getSkuAttrValueList().stream().forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                //应该能够获取到平台属性名、平台属性值名
                //应该页面自动获取
                //经过分析 可以不要AttrName 和 ValueName
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }
    }

    /**
     * 获取skuInfo列表
     * @param skuInfoPage
     * @return
     */
    @Override
    public IPage getList(Page<SkuInfo> skuInfoPage) {
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage, skuInfoQueryWrapper);
    }

    /**
     * 上架
     * @param skuId
     */
    @Override
    public void onSale(Long skuId) {
        //update sku_info set is_sale = 0 where id = 1;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
    }

    /**
     * 下架
     * @param skuId
     */
    @Override
    public void canceSale(Long skuId) {
        //update sku_info set is_sale = 1 where id = 1;
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
    }

    /**
     * 根据skuId获取skuInfo数据  通过Redisson做分布式锁
     * @param skuId
     * @return
     */
    @Override
    @GmallCache(prefix = "sku:")
    public SkuInfo getSkuInfo(Long skuId) {
        //判断缓存中是否有数据！ 直接从缓存获取，能够获取到就说明有数据，否则就没有数据
//        return getSkuInfoByRedisson(skuId); //通过redisson加分布式锁

//        return getSkuInfoByRedisLuo(skuId); //通过redis+luo脚本加锁
        return getSkuInfoDB(skuId);
    }

    //通过redisson加分布式锁
    private SkuInfo getSkuInfoByRedisson(Long skuId) {
        //定义缓存的key sku:skuId:info
        String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        try {
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //判断
            if(skuInfo==null){
                //如果为true  走数据库+加锁
                //定义一个锁的key  sku:skuId:lock
                String lockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                RLock lock = redissonClient.getLock(lockKey);
                //加上锁
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if(result){
                    try {
                        //执行业务逻辑
                        //从数据库获取
                        skuInfo = getSkuInfoDB(skuId);
                        //防止缓存穿透
                        if(skuInfo==null){
                            SkuInfo skuInfo1 = new SkuInfo();
                            //                    //代表存空值
                            //                    this.redisTemplate.opsForValue().set(skuKey, null,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            //                    return skuInfo;
                            //代表存空对象
                            this.redisTemplate.opsForValue().set(skuKey, skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        //数据库中有数据
                        this.redisTemplate.opsForValue().set(skuKey, skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo;
                    }finally {
                        lock.unlock();
                    }
                }else {
                    //没有获得锁的人
                    try {
                        Thread.sleep(100);
                        //自旋
                        return getSkuInfoDB(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }else {
                //缓存中有数据，直接返回
                return skuInfo;
            }
        } catch (InterruptedException e) {
            //记录日志
            e.printStackTrace();
        }
        //直接访问数据库
        return getSkuInfoDB(skuId);
    }


    //通过redis+luo脚本执行分布式锁
    private SkuInfo getSkuInfoByRedisLuo(Long skuId) {
        //定义缓存的key  sku:skuId:info
        String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        try {
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //判断
            if(skuInfo==null){
                //说明缓存中没有数据！ 查询数据库，并添加分布式锁的业务逻辑
                //redis+lua脚本
                String uuid = UUID.randomUUID().toString();
                //定义一个锁的key  sku:skuId:lock
                String lockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //加锁
                Boolean flag = this.redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                //flag = true 表示获取到了锁
                if(flag){
                    //执行业务逻辑
                    //从数据库获取
                    skuInfo = getSkuInfoDB(skuId);
                    //防止缓存穿透
                    if(skuInfo==null){
                        SkuInfo skuInfo1 = new SkuInfo();
    //                    //代表存空值
    //                    this.redisTemplate.opsForValue().set(skuKey, null,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
    //                    return skuInfo;
                        //代表存空对象
                        this.redisTemplate.opsForValue().set(skuKey, skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo1;
                    }
                    //数据库中有数据
                    this.redisTemplate.opsForValue().set(skuKey, skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                    //删除锁对象
                    //  准备一个lua 脚本！
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    //存储lua脚本
                    redisScript.setScriptText(script);
                    redisScript.setResultType(Long.class);
                    this.redisTemplate.execute(redisScript, Arrays.asList(lockKey),uuid);
                    return skuInfo;
                }else {
                    //没有获取到锁的人
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //自旋
                    return getSkuInfoDB(skuId);
                }
            }else {
                //缓存不为空
                return skuInfo;
            }
        } catch (Exception e) {
            //记录日志信息...
            e.printStackTrace();
        }
        //表示获取数据库中的数据
        return getSkuInfoDB(skuId);
    }

    /**
     * 从数据库获取数据
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoDB(Long skuId) {
        //获取skuInfo
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(skuInfo!=null){
            //需要skuImageList
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }


    /**
     * 根据skuId获取商品价格  获取最新的价格不需要加@GmallCache
     * @param skuId
     * @return
     */
    @Override
    public BigDecimal getPrice(Long skuId) {
        //select price from sku_info where id = sku_id;
        //不需要将数据放入缓存
        RLock lock = redissonClient.getLock(skuId + ":lock");
        //上锁
        lock.lock();
        SkuInfo skuInfo = null;
        BigDecimal price = new BigDecimal(0);
        try {
            QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
            skuInfoQueryWrapper.eq("id", skuId);
            skuInfoQueryWrapper.select("price");
            skuInfo = skuInfoMapper.selectOne(skuInfoQueryWrapper);
            if(skuInfo!=null){
               price = skuInfo.getPrice();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //解锁
            lock.unlock();
        }
        //返回价格
        return price;
    }

    /**
     * 根据三级分类id获取分类数据
     * @param category3Id
     * @return
     */
    @Override
    @GmallCache(prefix = "CategroyView:")
    public BaseCategoryView getCategroyView(Long category3Id) {
        //调用mapper层
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /**
     * 获取销售属性+销售属性值+锁定
     * @param spuId
     * @param skuId
     * @return
     */
    @Override
    @GmallCache(prefix = "SpuSaleAttrById:")
    public List<SpuSaleAttr> getSpuSaleAttrById(Long spuId, Long skuId) {
        //调用Mapper层
        return spuSaleAttrMapper.selectSpuSaleAttrById(spuId,skuId);
    }

    /**
     * 实现商品交换数据
     * @param spuId
     * @return
     */
    @Override
    @GmallCache(prefix = "ValueIdsAndSkuIdToMap:")
    public Map getValueIdsAndSkuIdToMap(Long spuId) {
        //声明map集合
        HashMap<Object, Object> hashMap = new HashMap<>();
        //获取销售属性值id 和 skuId
        //执行sql语句分析获取到 返回值应该是List<Map>
        List<Map> mapList = skuSaleAttrValueMapper.selectValueIdsAndSkuIdToMap(spuId);
        //判断
        if(!CollectionUtils.isEmpty(mapList)){
            mapList.stream().forEach(map -> {
                //循环遍历   首先根据表字段获取hashMap的key和value   然后添加
                hashMap.put(map.get("value_ids"),map.get("sku_id"));
            });
        }
        //返回数据
        return hashMap;
    }

    /**
     * 根据spuId获取海报集合
     * @param spuId
     * @return
     */
    @Override
    @GmallCache(prefix = "SpuPosterList:")
    public List<SpuPoster> getSpuPosterList(Long spuId) {
        //select * from spu_poster where spu_id = spuId;
        return spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id", spuId));
    }

    /**
     * 根据spuId获取商品的规格与包装数据
     * @param skuId
     * @return
     */
    @Override
    @GmallCache(prefix = "BaseAttrInfoList:")
    public List<BaseAttrInfo> getBaseAttrInfoList(Long skuId) {
        //调用Mapper层
        return baseAttrInfoMapper.selectBaseAttrInfoList(skuId);
    }

    /**
     * 获取首页数据
     * @return
     */
    @Override
    public List<JSONObject> getBaseCategoryList() {
        //声明一个集合
        List<JSONObject> list = new ArrayList<>();
        //一级，二级，三级分类数据
        //获取到所有的分类数据  base_category_view  视图
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        //分组去重  先按照一级分类id进行分组
        //map 的key = category1Id   Vlaue = List<BaseCategoryView>
        Map<Long, List<BaseCategoryView>> baseCategory1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //声明一个index变量
        int index = 1;
        //循环遍历
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = baseCategory1Map.entrySet().iterator();
        while (iterator.hasNext()){
            //创建一个对象
            JSONObject category1 = new JSONObject();
            //获取到Entey对象
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            Long category1Id = entry.getKey();
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();
            //一级分类Id
            category1.put("categoryId", category1Id);
            //一级分类name
            category1.put("categoryName", baseCategoryViewList1.get(0).getCategory1Name());
            //index  表示一级分类的第几项
            category1.put("index", index);
            //一级分类下还有CategoryChild，必须知道二级分类数据集合

            //index  迭代
            index++;

            //声明一个存储二级分类数据的集合
            List<JSONObject> category2Child = new ArrayList<>();
            //获取一级分类下的二级分类数据  二级分类数据在一级分类数据分组后的value里面  再次进行分组
            //key = category2Id   value = List<BaseCategoryView>
            Map<Long, List<BaseCategoryView>> baseCategory2Map = baseCategoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //循环遍历
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = baseCategory2Map.entrySet().iterator();
            while (iterator1.hasNext()){
                //声明一个对象
                JSONObject category2 = new JSONObject();
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                List<BaseCategoryView> baseCategoryViewList2 = entry1.getValue();
                Long category2Id = entry1.getKey();
                //赋值二级分类id
                category2.put("categoryId", category2Id);
                //赋值二级分类name
                category2.put("categoryName",baseCategoryViewList2.get(0).getCategory2Name());
                //存储二级分类数据
                category2Child.add(category2);

                //创建一个集合存储三级分类数据
                List<JSONObject> category3Child = new ArrayList<>();
                //获取三级分类id
                baseCategoryViewList2.forEach(baseCategoryView -> {
                    //创建一个对象
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", baseCategoryView.getCategory3Id());
                    category3.put("categoryName", baseCategoryView.getCategory3Name());
                    //存储三级分类数据
                    category3Child.add(category3);
                });
                //将三级分类数据保存到二级分类数据中
                category2.put("categoryChild",category3Child);
            }
            //将二级分类数据保存到一级分类数据中
            category1.put("categoryChild", category2Child);
            //将一级分类数据存储到集合中
            list.add(category1);
        }

        //返回数据
        return list;
    }

    /**
     * 通过品牌Id 来查询数据
     * @param tmId
     * @return
     */
    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        return baseTradeMarkMapper.selectById(tmId);
    }
}
